package swa23.provider.impl;
 
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import swa2012.telco.broker.Broker;
import swa2012.telco.broker.BrokerCallback;
import swa2012.telco.broker.beans.BrokerRegistrationStatus;
import swa2012.telco.broker.beans.Provider;
import swa23.provider.interfaces.ClientProvider;
import swa23.provider.interfaces.ClientRegistry;
import swa23.provider.interfaces.MessageRepository;
 
public class TelcoProvider {
	private static final String id = "swa-group-23";
	private static final Logger LOG = LoggerFactory.getLogger(TelcoProvider.class);
	public static final String BROKER_URI = "https://swa.univie.ac.at/TelcoBroker/BrokerService";
	//private final String id;
	private final Broker broker;
	private final BrokerCallback brokerCallback;
	private final ClientProvider clientProvider;
	private final ClientRegistry clientRegistry = new ClientRegistryImpl();
	private final MessageRepository messageRepository = new MessageRepositoryImpl();
	private Provider providerBean = null;
 
	public TelcoProvider(StringBuffer logString) {
	//this.id = id;
		this.clientProvider = new ClientProviderImpl(this, this.clientRegistry, this.messageRepository);
		this.brokerCallback = new BrokerCallbackImpl(this, this.clientRegistry, this.messageRepository);
 
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(Broker.class);
		factory.setAddress("https://swa.univie.ac.at/TelcoBroker/BrokerService");
 
		this.broker = ((Broker)factory.create());
		LOG.info(this + " started up TelcoProvider: " + this);
		}
 
		public BrokerCallback getBrokerCallback() {
			return this.brokerCallback;
		}
 
		public ClientProvider getClientProvider() {
			return this.clientProvider;
		}
 
		public Broker getBroker() {
			return this.broker;
		}
 
		public Provider getProviderBean() {
			return this.providerBean;
		}
 
		public void shutDown() {
			BrokerRegistrationStatus status = this.broker.deregisterProvider(this.providerBean);
			LOG.info("Deregistered from broker: " + status);
		}
 
		public void registerCallback(URI endpoint) {
			Utils.waitUntilAvailable(endpoint);
			this.providerBean = new Provider(id, endpoint);
			LOG.info("Registering at broker... " + this.providerBean);
 
			this.broker.deregisterProvider(this.providerBean);
			BrokerRegistrationStatus status = this.broker.registerProvider(this.providerBean);
			LOG.info("Registered at broker: " + status);
		}

		public void registerCallback(String endpoint) throws URISyntaxException {
			registerCallback(new URI(endpoint));
		}
 
		protected void finalize() throws Throwable {
			shutDown();
		}
}